package com.lhn.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * es 客户端-创建索引
 *
 * @author lhn
 * @date 2022/07/27 22:23
 * @since 1.0.0
 **/
public class ESTest_Doc_Insert {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient restHighLevelClient = null;
        try {
            restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("106.15.191.175", 9200, "http")));

            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index("user").id("1001");

            User user = new User();
            user.setName("李四");
            user.setAge(24);
            user.setSex("男");

            // 向 ES 中插入数据, 必须将数据格式转换成 JSON
            ObjectMapper mapper = new ObjectMapper();
            String asString = mapper.writeValueAsString(user);

            indexRequest.source(asString, XContentType.JSON);

            // 插入数据
            IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

            System.out.println(response.getResult());


        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            assert restHighLevelClient != null;
            restHighLevelClient.close();
        }
    }

}